package com.jy.api.controller;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * Created by hanxi on 2018/4/2.
 */
@RestController
public class SpeechController {
    private AipSpeech client;

    @GetMapping(path = "v1/pos/speech")
    public ResponseEntity<?> getSpeech(@RequestParam String tex, @RequestParam(required = false, defaultValue = "5") String spd, @RequestParam(required = false, defaultValue = "5") String pit, @RequestParam(required = false, defaultValue = "5") String vol, @RequestParam(required = false, defaultValue = "1") Integer per) {
        // 设置可选参数
        HashMap<String, Object> options = new HashMap<>();
        options.put("spd", spd);
        options.put("pit", pit);
        options.put("per", per);
        options.put("vol", vol);

        TtsResponse res = client.synthesis(tex, "zh", 1, options);
        byte[] data = res.getData();

        if (null != data) {
            return ResponseEntity.ok().contentType(MediaType.parseMediaType("audio/mp3")).body(data);
        } else {

            return ResponseEntity.status(500).contentType(MediaType.APPLICATION_JSON).body(res.getResult());
        }

    }

    @Autowired
    public void setClient(AipSpeech client) {
        this.client = client;
    }
}
